local extension = Package:new("investiture")
extension.extensionName = "tuntian_studio"

Fk:loadTranslationTable{
  ["investiture"] = "封神榜",
}

local U = require "packages/utility/utility"
local TT = require "packages/tuntian_studio/utility"
local R = require "packages/diy_utility/_base"
local DIY = require "packages/diy_utility/diy_utility"

--比干
local bigan = General(extension, "investiture__bigan", "shang", 3)

local function getbestRecordDamage(room)
  local damageEvents = room.logic:getActualDamageEvents(999, Util.TrueFunc, Player.HistoryRound)
  if #damageEvents > 0 then
    local curIndex = 1
    local bestRecord = {}
    local records = {}
    for j = curIndex, #damageEvents do
      curIndex = j
      local damageEvent = damageEvents[j]
      local damageData = damageEvent.data[1]
      if damageData.from then
        records[damageData.from.id] = (records[damageData.from.id] or 0) + damageData.damage
      end
    end
    for playerId, damage in pairs(records) do
      local curDMG = bestRecord.damage or 0
      if damage > curDMG then
        bestRecord = { playerIds = { playerId }, damage = damage }
      elseif damage == curDMG then
        table.insertIfNeed(bestRecord.playerIds, playerId)
      end
    end
    return bestRecord.playerIds
  end
  return {}
end

local LightningSkill = fk.CreateActiveSkill{
  name = "investiture__lightning_skill",
  prompt = "#lightning_skill",
  mod_target_filter = Util.TrueFunc,
  can_use = function(self, player, card)
    return not player:isProhibited(player, card)
  end,
  on_use = function(self, room, use)
    if not use.tos or #TargetGroup:getRealTargets(use.tos) == 0 then
      use.tos = { { use.from } }
    end
  end,
  on_effect = function(self, room, effect)
    local to = room:getPlayerById(effect.to)
    local judge = {
      who = to,
      reason = "lightning",
      pattern = ".|2~9|spade",
    }
    room:judge(judge)
    local result = judge.card
    if result.suit == Card.Spade and result.number >= 2 and result.number <= 9 then
      room:damage{
        to = to,
        damage = 3,
        card = effect.card,
        damageType = Fk:getDamageNature(fk.ThunderDamage) and fk.ThunderDamage or fk.NormalDamage,
        skillName = self.name,
      }
      room:moveCards{
        ids = room:getSubcardsByRule(effect.card, { Card.Processing }),
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonUse
      }
    else
      self:onNullified(room, effect)
    end
  end,
  on_nullified = function(self, room, effect)
    local player = room:getPlayerById(effect.to)
    if player:isProhibited(player, effect.card) then
      room:moveCards{
        ids = room:getSubcardsByRule(effect.card, { Card.Processing }),
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonPutIntoDiscardPile
      }
    else
      room:moveCards{
        ids = room:getSubcardsByRule(effect.card, { Card.Processing }),
        to = player.id,
        toArea = Card.PlayerJudge,
        moveReason = fk.ReasonPut
      }
    end
  end,
}

local Lightning = fk.CreateDelayedTrickCard{
  name = "&investiture__lightning",
  skill = LightningSkill,
  is_derived = true,
}

Lightning.package = extension
Fk:addSkill(LightningSkill)
Fk:addCard(Lightning)

local investiture__jijian = fk.CreateViewAsSkill{
  name = "investiture__jijian",
  anim_type = "control",
  pattern = "nullification",
  card_filter = function()
    return false
  end,
  view_as = function(self, cards)
    local card = Fk:cloneCard("nullification")
    card.skillName = self.name
    return card
  end,
  after_use = function(self, player, use)
    local room = player.room
    local current = room.current
    local players = getbestRecordDamage(room)
    if table.contains(players, current.id) then
      player:setSkillUseHistory(self.name, 0, Player.HistoryRound)
    elseif room:askForSkillInvoke(player, self.name, nil, "#investiture__jijian") then
      room:damage{
        from = player,
        to = current,
        damage = 1,
        skillName = self.name,
      }
      if player:isAlive() and current:isAlive() then
        room:damage{
          from = current,
          to = player,
          damage = 1,
          skillName = self.name,
        }
      end
      if not table.contains(getbestRecordDamage(room), current.id) then
        local n = 999
        for _, p in ipairs(room.alive_players) do
          n = math.min(n, p:getHandcardNum())
        end
        if current:getHandcardNum() > n then
          local cards = table.random(current:getCardIds("h"), current:getHandcardNum() - n)
          room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, nil, true, player.id)
        end
      end
    end
  end,
  enabled_at_response = function (self, player, response)
    return player:usedSkillTimes(self.name, Player.HistoryRound) == 0 and player.phase == Player.NotActive
  end,
}

local investiture__fengxin = fk.CreateTriggerSkill{
  name = "investiture__fengxin",
  frequency = Skill.Limited,
  mute = true,
  events = {fk.HpChanged},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      return player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and data.num < 0 and player.hp <= 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, self.name, "big")
    local lightning = room:printCard("investiture__lightning", Card.Heart, 12)
    room:moveCardTo(lightning, Card.PlayerJudge, player, fk.ReasonPut, self.name, nil, true)
    room:addCardMark(lightning, "__destr_discard")
    room:addCardMark(lightning, "investiture__fengxin")
    data.preventDying = true
  end,

  refresh_events = {fk.AskForPeachesDone, fk.BeforeCardsMove, fk.EventLoseSkill},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AskForPeachesDone then--濒死结算流程结束后
      if target == player and player:hasSkill(self) then
        return player.hp <= 0 and player.dying and (player:getMark(self.name) > 0 or table.find(player:getCardIds("j"), function (id)
          return Fk:getCardById(id):getMark("investiture__fengxin") > 0
        end))
      end
    elseif event == fk.BeforeCardsMove then
      if player:hasSkill(self) and player:isAlive() then
        if player:usedSkillTimes(self.name, Player.HistoryGame) > 0 then
          for _, move in ipairs(data) do
            local reason = move.moveReason
            if move.from and move.from == player.id and move.to and move.to ~= player.id then
              for _, info in ipairs(move.moveInfo) do
                if info.fromArea == Card.PlayerJudge then
                  if Fk:getCardById(info.cardId).trueName == "lightning" and Fk:getCardById(info.cardId):getMark("investiture__fengxin") > 0 then
                    return true
                  end
                end
              end
            end
          end          
        end
      end
    elseif event == fk.EventLoseSkill then
      return data == self
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AskForPeachesDone then
      room:setPlayerMark(player, self.name, 0)
      data.ignoreDeath = true
    elseif event == fk.BeforeCardsMove then
      for _, move in ipairs(data) do
        local ids = {}
        local new_info = {}
        for _, info in ipairs(move.moveInfo) do
          if Fk:getCardById(info.cardId).trueName == "lightning" and Fk:getCardById(info.cardId):getMark("investiture__fengxin") > 0 then
            table.insertIfNeed(ids, info.cardId)
          else
            table.insert(new_info, info)
          end
          if #ids > 0 then
            move.moveInfo = new_info
          end
        end
      end
    elseif event == fk.EventLoseSkill then
      if player.hp <= 0 then
        local dyingStruct = {
          who = player.id,
        }
        room:enterDying(dyingStruct)
      end
    end
  end,
}

bigan:addSkill(investiture__jijian)
bigan:addSkill(investiture__fengxin)

Fk:loadTranslationTable{
  ["investiture__bigan"] = "比干",
  ["#investiture__bigan"] = "木枯心匕",
  ["designer:investiture__bigan"] = "浩潇-淼龙",
  ["illustrator:investiture__bigan"] = "Jayron",
  ["cv:investiture__bigan"] = "浩潇-淼龙",

  ["investiture__jijian"] = "激谏",
  [":investiture__jijian"] = "轮次技，当你于回合外需要使用【无懈可击】时，你可视为使用之，然后若当前回合角色为本轮伤害最多，你重置此技能；否则，你可与其各对对方造成1点伤害，若其仍不为本轮造成伤害最多，你将其手牌弃置至与场上手牌数最小的角色相同。",
  ["#investiture__jijian"] = "你可与当前回合角色各对对方造成1点伤害",
  ["investiture__fengxin"] = "奉心",
  [":investiture__fengxin"] = "限定技，当你扣减体力至0后，你可将一张♥Q【闪电】置入判定区，若你的判定区内有此牌，你结算濒死后不会死亡；此【闪电】不能移动至其他角色的区域。",
  ["investiture__lightning"] = "闪电",
  ["investiture__lightning_skill"] = "闪电",
  [":investiture__lightning"] = "这是一张特制的闪电",

  ["$investiture__jijian1"] = "为人臣者，不得不以死争。",
  ["$investiture__jijian2"] = "主过不谏非忠也，畏死不言非勇也。",
  ["$investiture__fengxin"] = "人若是无心，如何？",
  ["~investiture__bigan"] = "妲己贱人！我死冥下见先帝无愧矣！",
}

local daji = General(extension, "investiture__daji", "shang", 3, 3, General.Agender)

local honeyTrapSkill = fk.CreateActiveSkill{
  name = "fire__honey_trap_skill",
  can_use = Util.CanUse,
  target_num = 1,
  mod_target_filter = function(self, to_select, selected, player, card, distance_limited)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return target ~= player and not target:isKongcheng() and target:isMale()
  end,
  target_filter = Util.TargetFilter,
  on_effect = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.to)
    local female = table.filter(room:getAlivePlayers(), function(p) return p:isFemale() end)
    if #female > 0 then
      for _, p in ipairs(female) do
        if target:isKongcheng() or target.dead then break end
        local id = room:askForCardChosen(p, target, "h", self.name)
        room:obtainCard(p, id, false, fk.ReasonPrey)
        if not player.dead and not p:isKongcheng() then
          local card = room:askForCard(p, 1, 1, false, self.name, false, ".", "#honey_trap-card:"..player.id)
          room:obtainCard(player, card[1], false, fk.ReasonGive)
        end
      end
    end
    local from, to = player, target
    if player:getHandcardNum() == target:getHandcardNum() then
      return
    elseif player:getHandcardNum() > target:getHandcardNum() then
      from, to = target, player
    end
    room:damage({
      from = from,
      to = to,
      card = effect.card,
      damage = 1,
      damageType = fk.FireDamage,
      skillName = self.name
    })
    if to == player then
      player:throwAllCards("h")
      room:endTurn()
      room:moveCardTo(room:printCard("crafty_escape", Card.Heart, 1), Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true)
      room:moveCardTo(room:printCard("crafty_escape", Card.Heart, 13), Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true)
    elseif to == target then
      local n = math.abs(player:getHandcardNum() - target:getHandcardNum())
      n = math.min(n, #target:getCardIds("he"))
      local ids = room:askForCardsChosen(player, target, n, n, "he", self.name, "fire__honey_trap-obtain:" .. n)
      if #ids > 0 then
        room:moveCardTo(ids, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, true, effect.from)
        local invoke = true
        while invoke do
          local use = U.askForUseRealCard(room, player, ids, ".|.|.|hand", self.name, "#investiture__chenpin-use")
          if not use then
            invoke = false
          end
        end
      end
    end
  end,
}
local honeyTrap = fk.CreateTrickCard{
  name = "&fire__honey_trap",
  skill = honeyTrapSkill,
  is_damage_card = true,
}

honeyTrap.package = extension
Fk:addSkill(honeyTrapSkill)
Fk:addCard(honeyTrap)

Fk:loadTranslationTable{
  ["fire__honey_trap"] = "美人计",
  ["fire__honey_trap_skill"] = "美人计",
  [":fire__honey_trap"] = "锦囊牌<br/><b>时机</b>：出牌阶段<br/><b>目标</b>：一名有手牌的其他男性角色<br/><b>效果</b>：所有女性角色获得目标角色的一张手牌"..
  "并交给你一张手牌，然后你与目标中手牌数少的角色对手牌数多的角色造成1点火焰伤害。",
  ["#honey_trap-card"] = "美人计：请将一张手牌交给 %src",
}

local chenpin = fk.CreateActiveSkill{
  name = "investiture__chenpin",
  prompt = "你可将性别变更为女",
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player.gender ~= General.Female
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:setPlayerProperty(player, "gender", General.Female)
    U.askForUseVirtualCard(room, player, "fire__honey_trap", nil, self.name)
  end
}

local yaoyuan = fk.CreateTriggerSkill{
  name = "investiture__yaoyuan",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if target == player and player:hasSkill(self) and data.card.is_damage_card then
      local use_event = room.logic:getCurrentEvent()
      local name = "jink"
      room.logic:getEventsByRule(GameEvent.UseCard, 1, function (e)
        if e.id < use_event.id then
          local use = e.data[1]
          if table.contains(TargetGroup:getRealTargets(use.tos), player.id) then
            name = use.card.name
            return true
          end
        end
      end, 0)
      return Fk:cloneCard(name).is_damage_card
    end
  end,
  on_use = function(self, event, target, player, data)
    --player.room:setPlayerProperty(player, "gender", General.Agender)
    TT.EnterHidden(player)
  end,
}

daji:addSkill(chenpin)
daji:addSkill(yaoyuan)

Fk:loadTranslationTable{
  ["investiture__daji"] = "妲己",
  ["#investiture__daji"] = "一笑蚀骨",
  ["designer:investiture__daji"] = "喜多芝士",
  ["investiture__chenpin"] = "晨牝",
  [":investiture__chenpin"] = "出牌阶段，你可将性别变更为女，然后视为使用一张<a href=':fire__honey_trap'>火【美人计】</a>。若因此受伤的角色："..
  "<br/>为你，你弃置所有手牌并结束回合，然后获得两张【金蝉脱壳】；"..
  "<br/>为目标角色，你获得其X张牌，然后你可以使用任意张其中可使用的牌（X为你与其手牌的差值）。",
  ["fire__honey_trap-obtain"] = "晨牝：请选择X张牌获得之",
  ["#investiture__chenpin-use"] = "晨牝：请选择使用的牌",
  ["investiture__yaoyuan"] = "妖怨",
  [":investiture__yaoyuan"] = "锁定技，当你成为伤害牌的目标后，若上一张目标包括你的牌也为伤害牌，你进入隐匿状态。",

  ["$investiture__chenpin1"] = "燃心魂焰！",
  ["$investiture__chenpin2"] = "灵狐惑心~",
  ["$investiture__yaoyuan1"] = "一法幻千面~",
  ["$investiture__yaoyuan2"] = "能解一族之祸，形神俱灭又如何？",
  ["~investiture__daji"] = "式微式微胡不归...",
}

local shangrong = General(extension, "investiture__shangrong", "shang", 3)

local investiture__gongtu = fk.CreateTriggerSkill{
  name = "investiture__gongtu",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target.phase == Player.Finish then
      local room = player.room
      local ids = {}
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
      local end_id = turn_event.id
      room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.DiscardPile and move.moveReason ~= fk.ReasonUse then
            for _, info in ipairs(move.moveInfo) do
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
      end, end_id)
      local cards = table.simpleClone(ids)
      for _, id in ipairs(cards) do
        if room:getCardArea(id) ~= Card.DiscardPile then
          table.removeOne(ids, id)
        end
      end
      self.cost_data = ids
      return #ids > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ids = room:askForCardsChosen(target, target, 1, 2, {card_data = {{self.name, self.cost_data}}}, self.name, "#investiture__gongtu")
    if #ids > 0 then
      room:moveCardTo(ids, Card.PlayerHand, target, fk.ReasonJustMove, self.name, nil, true)
    end
    if #room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
      local damage = e.data[5]
      if damage and target == damage.from then
        return true
      end
    end, Player.HistoryTurn) > 0 then
      local cards = room:askForCard(player, 2, 2, false, self.name, true, nil, "#investiture__gongtu-put")
      if #cards > 0 then
        room:moveCardTo(cards, Card.DrawPile, nil, fk.ReasonPut, self.name, nil)
        room:askForGuanxing(player, room:getNCards(2), {2, 2}, {0, 0})
      else
        room:loseHp(player, 1, self.name)
      end
    end
  end,
}

local investiture__qiangjian = fk.CreateActiveSkill{
  name = "investiture__qiangjian",
  anim_type = "support",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) <= player:getMark("investiture__qiangjian-turn")
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    target:drawCards(2, self.name)
    --
    if player == target then return end
    local card = room:askForCard(player, 1, 1, false, self.name, true, nil, "#investiture__qiangjian:"..target.id)
    if #card > 0 then
      room:useVirtualCard("sincere_treat", card, player, target, self.name, false)
      if #room:askForDiscard(target, 2, 2, true, self.name, true, nil, "#investiture__qiangjian-discard") > 0 then
        room:setPlayerMark(player, "investiture__qiangjian-turn", 1)
      end
    end
  end,
}
investiture__gongtu.CenterArea = true
shangrong:addSkill(investiture__gongtu)
shangrong:addSkill(investiture__qiangjian)

Fk:loadTranslationTable{
  ["investiture__shangrong"] = "商容",
  ["#investiture__shangrong"] = "亙古忠臣",
  ["designer:investiture__shangrong"] = "胖即是胖",
  ["investiture__gongtu"] = "巩土",
  [":investiture__gongtu"] = "一名角色的结束阶段，你可以令其获得至多两张本回合不因使用进入弃牌堆的牌，然后若其本回合造成过伤害，你需将两张牌置于牌堆顶或失去1点体力。",
  ["#investiture__gongtu"] = "请选择至多两张本回合不因使用进入弃牌堆的牌",
  ["#investiture__gongtu-put"] = "请将两张牌置于牌堆顶，否则失去1点体力",
  ["investiture__qiangjian"] = "强谏",
  [":investiture__qiangjian"] = "出牌阶段限一次，你可令一名其他角色摸两张牌，然后你可将一张牌当【推心置腹】对其使用。若如此做，其可弃置两张牌，将此技能于此回合改为出牌阶段限两次。",
  ["#investiture__qiangjian"] = "你可以将一张手牌当【推心置腹】对%src使用",
  ["#investiture__qiangjian-discard"] = "你可以弃置两张牌令“强谏”此回合改为出牌阶段限两次",

  ["$investiture__gongtu"] = "人总有一死，我商容死不足惜，只望我的苦口良言能令君觉醒，死亦足矣。",
  ["$investiture__qiangjian1"] = "大王，臣看着大王长大，又受先王重托扶政；虽告老还乡，但忠心未泯，今朝局混乱，特来进谏。",
  ["$investiture__qiangjian2"] = "昏君，你再执迷不悟，不思悔改，那好端端的锦绣山河，就会被你断送的干干净净，令先王在九泉之下寒心呐！",
  ["~investiture__shangrong"] = "帝乙仙君，臣有负于你，有负于社稷，不能匡国救君，臣愧于泉下见你...",
}

local dixin = General(extension, "investiture__dixin", "shang", 4)

function tableContainsAll(source, target)
  for _, v in ipairs(target) do  -- 遍历目标表
      local found = false
      for _, s in ipairs(source) do  -- 遍历源表
          if v == s then
              found = true
              break
          end
      end
      if not found then  -- 如果目标表中的元素在源表中没找到
          return false
      end
  end
  return true  -- 如果所有元素都找到了
end

local investiture__luochao = fk.CreateTriggerSkill{
  name = "investiture__luochao",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Discard then
      local targets = table.filter(player.room.alive_players, function (p) return player:canUseTo(Fk:cloneCard("fire_attack"), p) end)
      return #targets > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local targets = table.filter(player.room.alive_players, function (p) return player:canUseTo(Fk:cloneCard("fire_attack"), p) end)
    local tos = player.room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, #targets, "#investiture__luochao", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(self.cost_data, Util.Id2PlayerMapper)
    room:useVirtualCard("fire_attack", card, player, targets, self.name, false)
    local mark = player:getTableMark("luochao_player-turn")
    if tableContainsAll(mark, self.cost_data) then
      local n = math.min(#self.cost_data, #DIY.GetShownCards(player))
      local cards = room:askForCard(player, n, n, false, self.name, true, tostring(Exppattern{ id = DIY.GetShownCards(player) }), "#luochao-hide:::"..n)
      if #cards > 0 then
        DIY.HideCards(player, cards)
        room:addPlayerMark(player, "AddMaxCards-turn", n)
      end
      --room:endTurn()
    end
  end,

  refresh_events = {fk.Damage},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card and data.card.skillName == self.name
  end,
  on_refresh = function(self, event, target, player, data)
    local mark = player:getTableMark("luochao_player-turn")
    table.insertIfNeed(mark, data.to.id)
    player.room:setPlayerMark(player, "luochao_player-turn", mark)
  end
}

local investiture__niye = fk.CreateViewAsSkill{
  name = "investiture__niye",
  anim_type = "offensive",
  pattern = "archery_attack",
  card_filter = function(self, to_select, selected)
    return table.contains(DIY.GetShownCards(Self), to_select) and #selected < 2 and Fk:getCardById(to_select).color == Card.Red
  end,
  view_as = function(self, cards)
    if #cards ~= 2 then
      return nil
    end
    local c = Fk:cloneCard("archery_attack")
    c.skillName = self.name
    c:addSubcards(cards)
    return c
  end,
}

local niye_trigger = fk.CreateTriggerSkill{
  name = "#investiture__niye",
  events = {fk.BeforeDrawCard, fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    if event == fk.BeforeDrawCard then
      return player:hasSkill(self) and data.who == player and data.num ~= 0 and player:usedSkillTimes(self.name) == 0
    else
      if player:hasSkill(self) and target ~= player and player.room.current == player and player:getMark("@@investiture__niye") > 0 then
        return #table.filter(DIY.GetShownCards(player), function (id) return Fk:getCardById(id).color == Card.Black end) > 0
        and not target:prohibitUse(Fk:cloneCard("analeptic")) and not target:isProhibited(target, Fk:cloneCard("analeptic"))
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.BeforeDrawCard then
      return player.room:askForSkillInvoke(player, self.name)
    else
      return player.room:askForSkillInvoke(target, self.name, nil, "#niye-analeptic:"..player.id)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.BeforeDrawCard then
      data.num = 5
      room:addPlayerMark(player, "investiture__niye-temp")
    else
      while target.hp <= 0 do
        local cards = table.filter(DIY.GetShownCards(player), function (id) return Fk:getCardById(id).color == Card.Black end)
        local id = room:askForCardChosen(target, player, { card_data = {{self.name, cards}} }, self.name)
        if id then
          local card = Fk:cloneCard("analeptic")
          card.skillName = "investiture__niye"
          if player:hasSkill("investiture__guxuan") and target.kingdom == "shang" then--耦合
            DIY.HideCards(player, id)
          else
            card:addSubcard(id) 
          end
          room:useCard{
            from = target.id,
            tos = { { target.id } },
            extra_data = { analepticRecover = true },
            card = card,
          }
        end
      end
    end
  end,

  refresh_events = {fk.AfterCardsMove, fk.Deathed},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if player:hasSkill(self) and player:getMark("investiture__niye-temp") > 0 then
        for _, move in ipairs(data) do
          return move.to == player.id and move.toArea == Card.PlayerHand 
        end
      end
    else
      return player:hasSkill(self) and data.damage and data.damage.from == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      player.room:setPlayerMark(player, "investiture__niye-temp", 0)
      local cards = {}
      for _, move in ipairs(data) do
        for _, info in ipairs(move.moveInfo) do
          if player.room:getCardArea(info.cardId) == Card.PlayerHand then
            table.insertIfNeed(cards, info.cardId)
          end
        end
      end
      DIY.ShowCards(player, cards)
      player:filterHandcards()
    else
      player.room:addPlayerMark(player, "@@investiture__niye")
    end
  end,
}

local niye_effect = fk.CreateProhibitSkill{
  name = "#investiture__niye_effect",
  prohibit_use = function(self, player, card)
    if player:hasSkill(self) and card and card.color == Card.Red and card.skillName ~= "investiture__niye" then
      if card:isVirtual() then
        return table.find(card.subcards, function (id) return table.contains(DIY.GetShownCards(player), card:getEffectiveId()) end)
      else
        return table.contains(DIY.GetShownCards(player), card:getEffectiveId())
      end
    end
  end,
}

local niye_filter = fk.CreateFilterSkill{
  name = "#investiture__niye_filter",
  card_filter = function(self, to_select, player)
    return player:hasSkill(self.name) and to_select.color == Card.Black and player:getMark("@@investiture__niye") > 0
    and table.contains(DIY.GetShownCards(player), to_select:getEffectiveId())
  end,
  view_as = function(self, to_select)
    return Fk:cloneCard("analeptic", to_select.suit, to_select.number)
  end,
}

local investiture__guxuan = fk.CreateTriggerSkill{
  name = "investiture__guxuan$",
  frequency = Skill.Compulsory,
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      return (#DIY.GetShownCards(player) == 0 or #DIY.GetShownCards(player) == player:getHandcardNum()) and not player:isKongcheng()
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
    data.damage = data.damage + 1
  end,
}

investiture__niye:addRelatedSkill(niye_trigger)
investiture__niye:addRelatedSkill(niye_effect)
investiture__niye:addRelatedSkill(niye_filter)
dixin:addSkill(investiture__luochao)
dixin:addSkill(investiture__niye)
dixin:addSkill(investiture__guxuan)

Fk:loadTranslationTable{
  ["investiture__dixin"] = "帝辛",
  ["#investiture__dixin"] = "万醉同休",
  ["designer:investiture__dixin"] = "雪豹好困呀",
  ["investiture__luochao"] = "烙朝",
  [":investiture__luochao"] = "弃牌阶段开始时，你可视为对任意名角色使用【火攻】，若你以此法对这些角色均造成伤害，你暗置等同于这些角色数的手牌，此回合增加等量的手牌上限。",
  ["#investiture__luochao"] = "请选择任意名角色，视为对这些角色使用【火攻】",
  ["#luochao-hide"] = "请选择%arg张手牌暗置",
  ["investiture__niye"] = "溺业",
  ["@@investiture__niye"] = "<font color=\"#E8251E\"><b>溺业</b></font>",
  ["#investiture__niye"] = "溺业",
  ["#investiture__niye_filter"] = "溺业",
  ["#investiture__niye_effect"] = "溺业",
  [":investiture__niye"] = "回合技，当你摸牌时，可改为摸五张牌并明置。你使用红色明置牌仅能以两张牌转化【万箭齐发】的方式使用；你的回合内，若你杀死过角色，你的黑色明置牌视为【酒】，且濒死角色可以将你的一张黑色明置牌当【酒】②使用。",
  ["#niye-analeptic"] = "溺业：你可以将%src的一张黑色明置牌当【酒】使用",
  ["investiture__guxuan"] = "孤悬",
  [":investiture__guxuan"] = "主公技，你受到伤害时，若你的手牌均明置或均暗置，你摸一张牌并令此伤害+1；商势力角色触发“溺业”使用【酒】改为暗置你的黑色手牌。",

  ["$investiture__luochao1"] = "尔等既欲抱木就火，又何恐血散皮消？",
  ["$investiture__luochao2"] = "先剖其目，再拆其骨，温火焙之，最为受用，哈哈哈哈！",
  ["$investiture__niye1"] = "自汤武以来，百方无不靡伏，诸公何惧之有？",
  ["$investiture__niye2"] = "不过攀叶之虫，岂伤奔泥大象？",
  ["$investiture__guxuan1"] = "孤自知命端缜重，宸极寡伴，此乃天数也。",
  ["$investiture__guxuan2"] = "尔等食商之禄，则为孤之牛犬，安敢妄反！",
  ["~investiture__dixin"] = "悠悠此恨情无极，日落沧桑又万年...."
}

local feizhongyouhun = General(extension, "investiture__feizhongyouhun", "shang", 3)

local investiture__ninglu = fk.CreateTriggerSkill{
  name = "investiture__ninglu",
  events = {fk.AfterCardsMove, fk.AfterDrawInitialCards},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        return move.from == player.id and move.extra_data and #move.extra_data.ninglu > 0
      end
    else
      return target == player
    end
  end,
  on_use = function (self, event, target, player, data)
    if player:isKongcheng() then
      local cards = player:drawCards(1, self.name)
      DIY.ShowCards(player, cards)
    else
      local hidecards = table.filter(player:getCardIds("h"), function (id) return not table.contains(DIY.GetShownCards(player), id) end)
      if #hidecards > 0 then
        local cards = player.room:askForCard(player, 1, 999, false, self.name, false, tostring(Exppattern{ id = hidecards }), "#ninglu-show")
        if #cards > 0 then
          DIY.ShowCards(player, cards)
        end   
      end
    end
  end,

  refresh_events = {fk.BeforeCardsMove},
  can_refresh = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.from and move.from == player.id then
        for _,info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand and table.contains(DIY.GetShownCards(player), info.cardId) then
            return true
          end
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local ids = {}
    for _, move in ipairs(data) do
      for _, info in ipairs(move.moveInfo) do
        table.insertIfNeed(ids, info.cardId)
      end
      if table.every(DIY.GetShownCards(player), function (id) return table.contains(ids, id) end) then
        move.extra_data = move.extra_data or {}
        move.extra_data.ninglu = ids
      end
    end
  end,
}

local investiture__cangji = fk.CreateTriggerSkill{
  name = "investiture__cangji",
  events = {fk.BeforeCardsMove},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    for _, move in ipairs(data) do
      if move.from and move.from == player.id and move.moveReason == fk.ReasonUse and (#DIY.GetShownCards(player) + 1 == player:getHandcardNum()) then
        local use = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard,true).data[1]
        if (not use.card:isVirtual() or #use.card.subcards == 0) and use.card.type ~= Card.TypeEquip and use.card.sub_type ~= Card.SubtypeDelayedTrick then
          for _,info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand and not table.contains(DIY.GetShownCards(player), info.cardId) then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    for _, move in ipairs(data) do
      for _, info in ipairs(move.moveInfo) do
        DIY.ShowCards(player,{info.cardId})
        --player.room:setPlayerMark(player, "@$investiture__cangji", {info.cardId})
      end
      local use = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true).data[1]
      if (not use.card:isVirtual() or #use.card.subcards == 0) and use.card.type ~= Card.TypeEquip and use.card.sub_type ~= Card.SubtypeDelayedTrick then
        player:addCardUseHistory(use.card.trueName, -1)
      end
      move.moveInfo = {}
    end
  end,
}

local investiture__jigou = fk.CreateTriggerSkill{
  name = "investiture__jigou",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.extra_data and data.extra_data.jigou
    and data.extra_data.jigou == player:getHandcardNum()
  end,
  on_cost = function(self, event, target, player, data)
    local targets = player.room:askForChooseToMoveCardInBoard(player, "#investiture__jigou-move", self.name, true, nil)
    if #targets ~= 0 then
      self.cost_data = targets
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local targets = table.map(self.cost_data, function(id) return player.room:getPlayerById(id) end)
    player.room:askForMoveCardInBoard(player, targets[1], targets[2], self.name)
  end,

  refresh_events = {fk.PreCardUse},
	can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player
	end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    data.extra_data = data.extra_data or {}
    data.extra_data.jigou = player:getHandcardNum()
  end,
}

feizhongyouhun:addSkill(investiture__ninglu)
feizhongyouhun:addSkill(investiture__cangji)
feizhongyouhun:addSkill(investiture__jigou)

Fk:loadTranslationTable{
  ["investiture__feizhongyouhun"] = "费仲尤浑",
  ["#investiture__feizhongyouhun"] = "表里弄权",
  ["designer:investiture__feizhongyouhun"] = "易大剧",
  ["investiture__ninglu"] = "佞禄",
  [":investiture__ninglu"] = "锁定技，分发起始手牌或你失去最后的明置手牌后，若你没有手牌，你摸一张牌并明置之，否则你须明置至少一张手牌。",
  ["#ninglu-show"] = "佞禄：请明置至少一张手牌",
  ["investiture__cangji"] = "藏计",
  ["@$investiture__cangji"] = "藏计",
  [":investiture__cangji"] = "若你唯一暗置的手牌为即时牌，你使用此牌时可改为明置，且你以此法使用的牌不计入次数限制。",
  ["investiture__jigou"] = "机彀",
  [":investiture__jigou"] = "你使用牌后，若手牌数与使用此牌前相同，则你可移动场上的一张牌。",
  ["#investiture__jigou-move"] = "你可移动场上的一张牌",
}

local boyikao = General(extension, "investiture__boyikao", "zhou", 3)

local djb__jingchen = fk.CreateTriggerSkill{
  name = "djb__jingchen",
  anim_type = "defensive",
  events = {fk.TargetSpecified, fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if event == fk.TargetSpecified then
      return player:hasSkill(self) and table.contains(U.getActualUseTargets(player.room, data, event), player.id) and 
      #AimGroup:getAllTargets(data.tos) > 1 and data.firstTarget and player:usedSkillTimes(self.name, Player.HistoryRound) == 0
    else
      return player:hasSkill(self, true, true) and data.extra_data and data.extra_data.jingchen and #data.extra_data.jingchen > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TargetSpecified then
      local targets = U.getActualUseTargets(player.room, data, event)
      table.removeOne(targets, player.id)
      local tos = player.room:askForChoosePlayers(player, targets, 1, #targets, "#djb__jingchen-invoke:::"..data.card:toLogString(), self.name, true)
      if #tos > 0 then
        self.cost_data = tos
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecified then
      table.insertTableIfNeed(data.nullifiedTargets, self.cost_data)
      data.extra_data = data.extra_data or {}
      data.extra_data.jingchen = self.cost_data
    else
      local players = data.extra_data.jingchen
      for _, p in ipairs(players) do
        p = room:getPlayerById(p)
        if not p.dead then
          p:drawCards(1, self.name)
          local targets = {}
          if not player.dead then table.insertIfNeed(targets, player.id) end
          if not room:getPlayerById(data.from).dead then table.insertIfNeed(targets, data.from) end
          if #targets > 0 then
            local tos, cards = room:askForChooseCardsAndPlayers(p, 1, 1, targets, 1, 1,
            ".", "#djb__jingchen-give:"..player.id..":"..data.from, self.name, false)
            room:moveCardTo(cards, Card.PlayerHand, room:getPlayerById(tos[1]), fk.ReasonGive, self.name, nil, false)
          end
        end
      end
    end
  end,
}

local djb__liwei = fk.CreateTriggerSkill{
  name = "djb__liwei",
  --anim_type = "masochism",
  mute = true,
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and (target == player or player:getMark("@@djb__liwei-round") > 0)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if target == player then
      local targets = room:getOtherPlayers(player)
      player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
        local damage = e.data[5]
        if damage and table.contains(targets, damage.to) then
          table.removeOne(targets, damage.to)
        end
      end, Player.HistoryTurn)
      local user, cards = U.askForRaceDiscard(room, targets, 1, 1, false, self.name, "peach,pear", "#djb__liwei-use:"..player.id, true)
      if #cards > 0 then
        local card = Fk:getCardById(cards[1])
        if not user:isProhibited(player, card) then
          room:notifySkillInvoked(player, self.name, "masochism")
          player:broadcastSkillInvoke(self.name)
          room:useCard({
            card = card,
            from = user.id,
            tos = {{player.id}},
            skillName = self.name,
          })
          user:drawCards(2, self.name)
        end
      end
    elseif player:getMark("@@djb__liwei-round") > 0 then
      if target:isAlive() then
        local cards = room:askForCard(player, 1, 1, true, self.name, true, "peach,pear", "#djb__liwei-use:"..target.id)
        if #cards > 0 then
          local card = Fk:getCardById(cards[1])
          if not player:isProhibited(target, card) then
            room:notifySkillInvoked(player, self.name, "support")
            player:broadcastSkillInvoke(self.name)
            room:useCard({
              card = card,
              from = player.id,
              tos = {{target.id}},
              skillName = self.name,
            })
            player:drawCards(2, self.name)
          end
        end
      end
    end
  end,

  refresh_events = {fk.AfterRoundEnd, fk.RoundStart},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterRoundEnd then
      return player:hasSkill(self) and #player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
        local damage = e.data[5]
        if damage and damage.to == player then
          return true
        end
      end, Player.HistoryRound) == 0
    else
      return player:getMark("djb__liwei-record") > 0
    end
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.AfterRoundEnd then
      player.room:addPlayerMark(player, "djb__liwei-record")
    else
      player.room:setPlayerMark(player, "djb__liwei-record", 0)
      player.room:addPlayerMark(player, "@@djb__liwei-round")
    end
  end,
}

local djb__haitu = fk.CreateTriggerSkill{
  name = "djb__haitu",
  anim_type = "support",
  events = {fk.Death},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self, true, true) and player.room:getBanner("@$CenterArea")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local names = {"peach", "analeptic", "pear", "god_salvation"}
    local cards = table.filter(player.room:getBanner("@$CenterArea"), function (id) return table.contains(names, Fk:getCardById(id).trueName) end)
    if #cards > 0 then
      room:askForYiji(player, cards, room:getAlivePlayers(), self.name, #cards, #cards, "#djb__haitu", cards)
    end
  end,
}

djb__haitu.CenterArea = true
boyikao:addSkill(djb__jingchen)
boyikao:addSkill(djb__liwei)
boyikao:addSkill(djb__haitu)

Fk:loadTranslationTable{
  ["investiture__boyikao"] = "伯邑考",
  ["#investiture__boyikao"] = "怀信侘傺",
  ["designer:investiture__boyikao"] = "淼龙",
  ["cv:investiture__boyikao"] = "淼龙",
  ["djb__jingchen"] = "靖尘",
  [":djb__jingchen"] = "轮次技，当一名角色使用牌指定所有目标后，若之目标大于1且包括你，你可令此牌对任意名其他角色无效。若如此做，之结算后，这些角色各摸一张牌并交给你或使用者一张牌。",
  ["#djb__jingchen-invoke"] = "你可令%arg对任意名目标角色无效",
  ["#djb__jingchen-give"] = "靖尘：请交给%src或%dest一张牌",
  ["djb__liwei"] = "立危",
  ["@@djb__liwei-round"] = "立危",
  [":djb__liwei"] = "当你受到伤害后，本回合未受到过伤害的角色可<a href=':compete'>竞争</a>对你使用【桃】或【梨】并摸两张牌；若你于一轮内未受到伤害，你于下一轮内可对其他角色发动“立危”。",
  ["#djb__liwei-use"] = "立危：你可以对%src使用【桃】或【梨】并摸两张牌",
  ["djb__haitu"] = "醢兔",
  [":djb__haitu"] = "你死亡时，可分配中央区内能恢复体力的牌。",
  ["#djb__haitu"] = "你可以分配中央区内能恢复体力的牌",
  [":compete"] = "同无懈可击的抢答机制",

  ["$djb__jingchen1"] = "粟撒西疆土，不教烽烟近镐京！",
  ["$djb__jingchen2"] = "仁者非无刃，止战之刃藏琴匣！",
  ["$djb__liwei1"] = "父侯羑里卦象凶，自有长子上祭坛！",
  ["$djb__liwei2"] = "三牲太牢宴朝歌，何妨添我血肉羹",
  ["$djb__haitu1"] = "肉酱可饲狐，神魂早归封神台。",
  ["$djb__haitu2"] = "剁骨成泥日，正是白兔跃月时！",
  ["~investiture__boyikao"] = "西岐麦穗垂首处，皆是长公子骨血...",
}

-- 鄂崇禹
local echongyu = General(extension, "investiture__echongyu", "shang", 4)
TT.loadGeneral(echongyu, { name = "鄂崇禹", reputation = "髮上指冠", designer = "凛冬之风镇魂曲", illustrator = "Jayron" })

--- 饮盏
local yinzhan = fk.CreateViewAsSkill {
  name = "investiture__yinzhan",
  anim_type = "support",
  pattern = "analeptic",
  card_filter = Util.FalseFunc,
  before_use = function (self, player, use)
    local room = player.room
    room:handleAddLoseSkills(player, "#yinzhan_delay")
    room:addPlayerMark(player, "@@yinzhan_drunk-turn", player:getHandcardNum())
  end,
  view_as = function (self, cards, player)
    local card = Fk:cloneCard("analeptic")
    card:addSubcards(player:getCardIds("h"))
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function (self, player)
    return not player:isKongcheng()
  end,
  enabled_at_response = function (self, player, response)
    return not (player:isKongcheng() or response)
  end,
}

TT.loadSkill(yinzhan, {
  name = "饮盏",
  detail = "你可以将所有手牌当一张【酒】使用，本回合鄂崇禹下次造成伤害后，拥有“引盏”的角色摸此次转化牌数张牌。"
})

echongyu:addSkill(yinzhan)

local yinzhan_delay = fk.CreateTriggerSkill {
  name = "#yinzhan_delay",
  anim_type = "drawcard",
  events = {fk.Damage},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark("@@yinzhan_drunk-turn") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local num = player:getMark("@@yinzhan_drunk-turn")
    room:setPlayerMark(player, "@@yinzhan_drunk-turn", 0)
    local tos = table.filter(room.alive_players, function (p) return p:hasSkill(yinzhan) end)
    if #tos == 0 then return end
    for _, p in ipairs(tos) do
      if not p.dead then
        p:drawCards(num, self.name)
      end
    end
  end,
}
Fk:addSkill(yinzhan_delay)

Fk:loadTranslationTable {
  ["#yinzhan_delay"] = "饮盏",
  ["@@yinzhan_drunk-turn"] = "饮盏",
}

--- 怒号
local nuhao = fk.CreateActiveSkill {
  name = "investiture__nuhao",
  anim_type = "offensive",
  prompt = "#investiture__nuhao_prompt",
  can_use = function (self, player, card, extra_data)
    return player:hasSkill(yinzhan)
  end,
  card_filter = Util.FalseFunc,
  target_num = 1,
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data, player)
    local room = Fk:currentRoom()
    return #selected == 0 and not room:getPlayerById(to_select):hasSkill(yinzhan)
  end,
  on_use = function (self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:handleAddLoseSkills(player, "-investiture__yinzhan")
    room:handleAddLoseSkills(target, "investiture__yinzhan")
    room:setPlayerMark(target, "yinzhan_player", 1)
    room.logic:getCurrentEvent():findParent(GameEvent.Turn, true, Player.HistoryGame):addExitFunc(function ()
      room:handleAddLoseSkills(player, "investiture__yinzhan")
      room:handleAddLoseSkills(target, "-investiture__yinzhan")
    end)
    if not player.dead then
      local card = Fk:cloneCard("slash")
      card.skillName = self.name
      if U.getDefaultTargets(player, card, true, true) then
        local able_players = table.filter(room.alive_players, function (p)
          return player:canUseTo(card, p, { bypass_distances = true, bypass_times = true })
        end)
        local to = room:askForChoosePlayers(player, table.map(able_players, Util.IdMapper), 1, 1, "#nuhao_attack", self.name, false, true)
        if #to == 1 then
          room:useCard {
            card = card,
            from = player.id,
            tos = { to },
            extraUse = true,
          }
        end
      end
    end
  end,
}

TT.loadSkill(nuhao, {
  name = "怒号",
  detail = "出牌阶段，你可以将“饮盏”于本回合交给一名其他角色并视为对一名角色使用【杀】。若二者为相同角色，之不能被响应。"
})

echongyu:addSkill(nuhao)

local nuhao_delay = fk.CreateTriggerSkill {
  name = "#nuhao_delay",
  mute = true,
  events = {fk.PreCardUse},
  can_trigger = function(self, event, target, player, data)
    return player == target and data.card.skillName and data.card.skillName == "investiture__nuhao"
  end,
  on_trigger = function(self, event, target, player, data)
    local room = player.room
    local yinzhan_player = table.filter(room.alive_players, function (p)
      return p:getMark("yinzhan_player") == 1
    end)
    local list = data.disresponsiveList or {}
    for _, p in ipairs(yinzhan_player) do
      room:setPlayerMark(p, "yinzhan_player", 0)
      table.insertIfNeed(list, p.id)
    end
    data.disresponsiveList = list
  end,
}
nuhao:addRelatedSkill(nuhao_delay)

Fk:loadTranslationTable {
  ["#investiture__nuhao_prompt"] = "你想要发动“怒号”将“饮盏”交给一名其他角色吗？",
  ["#nuhao_attack"] = "怒号：视为对一名角色使用【杀】",
  ["#nuhao_delay"] = "怒号",
}

-- 崇侯虎
local chonghouhu = General(extension, "investiture__chonghouhu", "shang", 3)
TT.loadGeneral(chonghouhu, { name = "崇侯虎", reputation = "焚戢恶廈", designer = "胖即是胖", illustrator = "Jayron", cv = "易大剧", dead = "呃...善恶到头终有报？" })

--- 浩筑
local haozhu = fk.CreateTriggerSkill {
  name = "investiture__haozhu",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    return (target == player and target.phase == Player.Judge) or ( (target == player or player:getMark(self.name) == 0) and target.phase == Player.Draw)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Judge then
      player:broadcastSkillInvoke(self.name, math.random(1,2))
      room:notifySkillInvoked(player, self.name, "negative")
      local judge = {
        who = player,
        reason = "lightning",
        pattern = ".|2~9|spade",
      }
      room:judge(judge)
      local result = judge.card
      if result.suit == Card.Spade and result.number >= 2 and result.number <= 9 then
        room:damage{
          to = player,
          damage = 3,
          damageType = Fk:getDamageNature(fk.ThunderDamage) and fk.ThunderDamage or fk.NormalDamage,
          skillName = "lightning",
        }
      end
    else
      player:broadcastSkillInvoke(self.name, math.random(3,4))
      room:notifySkillInvoked(player, self.name, "drawcard")
      local cards = room:getNCards(3)
      room:moveCards{
        ids = cards,
        toArea = Card.Processing,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        proposer = target.id,
      }
      if not player.dead then
        local card = room:askForCardsChosen(player, target, 1, 1, {card_data = {{self.name, cards},} }, self.name, "#haozhu_claim:"..target.id )[1]
        if card then
          TT.premeditate(player, card, self.name, player.id)
        end
        if not target.dead then
          room:obtainCard(target, table.filter(cards, function (c) return c ~= card end), false, fk.ReasonJustMove, target.id, self.name)
        end
      end
    end
    return true
  end,

  refresh_events = {fk.AfterDrawPileShuffle},
  can_refresh = function(self, event, target, player, data)
    return player:getMark(self.name) == 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addPlayerMark(player, self.name, 1)
  end,
}

TT.loadSkill(haozhu, {
    name = "浩筑",
    detail = "锁定技，①判定阶段，你改为进行一次【闪电】的判定；②摸牌阶段，你改为亮出牌堆顶的三张牌，然后令崇侯虎蓄谋其中一张牌，你获得其余的牌；③若牌堆未洗过牌，则其他角色的摸牌阶段需执行②。",
    voices  = { "轰天炮响，汪洋大海起春雷。", "振地锣鸣，万仞山前丢霹雳。", "三丁抽二，独丁赴役！", "此台功成浩瀚，要动无限钱粮！", }
})

chonghouhu:addSkill(haozhu)

--- 揽贿
local lanhui = fk.CreateActiveSkill {
  name = "investiture__lanhui",
  anim_type = "control",
  prompt = "#investiture__lanhui",
  can_use = function(self, player, card, extra_data)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_num = 2,
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data, player)
    local target = Fk:currentRoom():getPlayerById(to_select)
    if #selected == 0 then
      return #target:getCardIds("ej") > 0
    elseif #selected == 1 then
      return Fk:currentRoom():getPlayerById(selected[1]):canMoveCardsInBoardTo(target)
    end
    return false
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local tos = table.map(effect.tos, function (id) return room:getPlayerById(id) end)
    local move = room:askForMoveCardInBoard(player, tos[1], tos[2], self.name, nil)
    if move and move.card and move.from then
      local from_player = room:getPlayerById(move.from)
      if from_player:getMark(self.name) == 1 then
        room:setPlayerMark(from_player, self.name, 0)
        if from_player == player then
          player:drawCards(2, self.name)
        else
          local card = Fk:cloneCard("tuntian__enemy_at_the_gates")
          card.skillName = self.name
          if not (from_player:prohibitUse(card) or from_player:isProhibited(player, card)) and room:askForSkillInvoke(from_player, self.name, nil, "#lanhu_offense:"..player.id) then
            room:useCard {
              card = card,
              from = move.from,
              tos = { {player.id} },
              skillName = self.name,
            }
          end
        end
      end
    end
  end,
}
local lanhui_delay = fk.CreateTriggerSkill {
  name = "#lanhui_delay",
  refresh_events = {fk.AfterCardsMove},
  can_refresh = function (self, event, target, player, data)
    if not player:hasSkill(self) then return end
    for _, move in ipairs(data) do
      if move.skillName == lanhui.name then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerJudge then
            return true
          end
        end
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(room:getPlayerById(data[1].from), lanhui.name, 1)
  end,
}
lanhui:addRelatedSkill(lanhui_delay)

TT.loadSkill(lanhui, {
    name = "揽贿",
    detail = "出牌阶段限一次，你可以移动场上的一张牌，然后若因此失去场上的牌的角色：为你，你摸两张牌；不为你，其可以视为对你使用一张【兵临城下】。",
    voices = { "逢君欲作千年调，买窟惟知百计要。" ,"奉命督工人力尽，剥民膏髓自肥饶~", }
})

chonghouhu:addSkill(lanhui)

Fk:loadTranslationTable {
  ["#haozhu_claim"] = "浩筑：选择一张牌蓄谋",
  ["#investiture__lanhui"] = "你想要发动“揽贿”移动场上的一张牌吗？",
  ["#lanhu_offense"] = "揽贿：是否视为对 %src 使用【兵临城下】",
}

local wenzhong = General(extension, "investiture__wenzhong", "shang", 4)

local function doThunder(player)
  local judge = {
    who = player,
    reason = "lightning",
    pattern = "spade",
  }
  player.room:judge(judge)
  local result = judge.card
  if result.suit == Card.Spade then
    player.room:damage{
      to = player,
      damage = 2,
      damageType = fk.ThunderDamage,
      skillName = "lightning",
    }
    return true
  else
    return false
  end
end

local huiyu = fk.CreateTriggerSkill {
  name = "investiture__huiyu",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player == target and player:hasSkill(self) and ((player.phase == Player.Start and player:getMark("@@investiture__huiyu") == 0)
     or player.phase == Player.Judge)
  end,
  on_cost = function (self, event, target, player, data)
    if player.phase == Player.Start then
      local targets = table.map(player.room:getOtherPlayers(player), Util.IdMapper)
      local tos = player.room:askForChoosePlayers(player, targets, 1, 1, "#djb__huiyu-invoke", self.name, true)
      if #tos > 0 then
        self.cost_data = tos[1]
        return true
      end
    else
      return player.room:askForSkillInvoke(player, self.name, nil)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Judge then
      local fault = false
      if player:getMark("@@investiture__huiyu") == 0 then
        fault = doThunder(player)
      else
        local use = U.askForUseVirtualCard(room, player, "lvs_thunder__slash", nil, self.name)
        if use then
          fault = use.damageDealt
        end
      end
      local n = 0
      if fault then n = 1 end
      if player:getMark("@@investiture__huiyu") == 0 then
        local use = U.askForUseVirtualCard(room, player, "lvs_thunder__slash", nil, self.name, "#investiture__huiyu", true, true, true, true, {}, true)
        if use then
          use = {
            card = Fk:cloneCard("thunder__slash"),
            from = use.from,
            tos = use.tos,
            extraUse = true,
          }
          use.card.skillName = self.name
          use.additionalEffect = (use.additionalEffect or 0) + n
          player.room:useCard(use)
        end
      else
        for i = 0, n do
          doThunder(player)
        end
      end
    else
      local to = room:getPlayerById(self.cost_data)
      room:addPlayerMark(to, "@@dawu")
      room:addPlayerMark(player, "@@kuangfeng")
      room:addPlayerMark(player, "@@investiture__huiyu")
    end
  end,
}

local huiyu_buff = fk.CreateTriggerSkill{
  name = "#investiture__huiyu_buff",
  events = {fk.DamageInflicted},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self, true, true) then return false end
    return (target:getMark("@@kuangfeng") > 0 and data.damageType == fk.FireDamage)
    or (target:getMark("@@dawu") > 0 and data.damageType ~= fk.ThunderDamage)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    if target:getMark("@@kuangfeng") > 0 and data.damageType == fk.FireDamage then
      data.damage = data.damage + 1
    end
    if target:getMark("@@dawu") > 0 and data.damageType ~= fk.ThunderDamage then
      return true
    end
  end,

  refresh_events = {fk.AfterSkillEffect},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self, true, true) and data.name == self.name
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    table.forEach(room.alive_players, function(p)
      room:removePlayerMark(p, "@@kuangfeng")
      room:removePlayerMark(p, "@@dawu")
     end)
     if not player.dead then
        room:setPlayerMark(player, "@@investiture__huiyu", 0)
     end
  end,
}

local bugun = fk.CreateTriggerSkill{
  name = "investiture__bugun",
  anim_type = "special",
  events = {fk.StartJudge},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and player:usedSkillTimes(self.name) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local targets = table.map(table.filter(player.room.alive_players, function (p) return not p:isNude() end), Util.IdMapper)
    local tos = player.room:askForChoosePlayers(player, targets, 1, 1, "#djb__bugun-invoke", self.name, true)
    if #tos > 0 then
      self.cost_data = tos[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local id = room:askForCardChosen(player, to, "he", self.name)
    if id then
      room:moveCardTo(id, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, player.id)
      local topid = room:getNCards(1)[1]
      room:moveCardTo(topid, Card.DiscardPile, nil, fk.ReasonDiscard, self.name, "", true, player.id)
      local ids, choice = U.askforChooseCardsAndChoice(player, {id, topid}, {"OK"}, self.name, "#djb__bugun-choose")
      if #ids > 0 then
        data.card = Fk:getCardById(ids[1])
        data.card.skillName = self.name
      end
      if data.card.suit == Card.Spade then
        local players = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 3, "#djb__bugun-chained", self.name, false)
        table.forEach(players, function (p) return room:getPlayerById(p):setChainState(true) end)
      end
      if player == to then
        local ids = room:getNCards(2)
        while true do
          room:setPlayerMark(player, "yiji_cards", ids)
          local _, ret = room:askForUseActiveSkill(player, "yiji_active", "#bugun-give", true, nil, true)
          room:setPlayerMark(player, "yiji_cards", 0)
          if ret then
            for _, id in ipairs(ret.cards) do
              table.removeOne(ids, id)
            end
            room:moveCardTo(ret.cards, Card.PlayerHand, room:getPlayerById(ret.targets[1]), fk.ReasonGive,
            self.name, nil, false, player.id, nil, player.id)
            if #ids == 0 then break end
            if player.dead then
              room:moveCards({
                ids = ids,
                toArea = Card.DiscardPile,
                moveReason = fk.ReasonJustMove,
                skillName = self.name,
              })
              break
            end
          else
            room:moveCardTo(ids, Player.Hand, player, fk.ReasonGive, self.name, nil, false, player.id)
            break
          end
        end
      end
    end
  end,
}

huiyu:addRelatedSkill(huiyu_buff)
wenzhong:addSkill(huiyu)
wenzhong:addSkill(bugun)

Fk:loadTranslationTable {
  ["investiture__wenzhong"] = "闻仲",
  ["designer:investiture__wenzhong"] = "屑",
  ["#investiture__wenzhong"] = "",
  ["investiture__huiyu"] = "晖煜",
  ["@@investiture__huiyu"] = "晖煜修改",
  ["#djb__huiyu-invoke"] = "晖煜：你可令一名其他角色获得“大雾”标记，你获得“狂风”标记",
  [":investiture__huiyu"] = "判定阶段，你可先判定一次<a href=':floating_mine'>【浮雷】</a>，再视为使用一张雷【杀】，若前者生效，则后者额外结算一次；准备阶段，你可交换视为使用牌与判定的顺序，令一名其他角色获得“大雾”标记，你获得“狂风”标记，直到其中一个标记发动效果。",
  ["#investiture__huiyu"] = "请视为使用雷【杀】",
  ["investiture__bugun"] = "补衮",
  [":investiture__bugun"] = "回合技，当你判定时，可以弃置牌堆顶与一名角色各一张牌，你选择其中一张作为判定牌。若之为黑桃/你的牌，则你横置至多三名角色/观看并分配牌堆顶两张牌。",
  ["#djb__bugun-invoke"] = "补衮：你可弃置一名角色的一张牌",
  ["#djb__bugun-choose"] = "补衮：请选择一张牌作为判定牌",
  ["#djb__bugun-chained"] = "补衮：横置至多三名角色",
  ["#bugun-give"] = "补衮：请分配牌堆顶两张牌，点取消则自己获得",
  ["@@kuangfeng"] = TT.colorString("狂风", "#FF4433"),
  ["@@dawu"] = TT.colorString("大雾", "#7393B3"),
  [":floating_mine"] = "延时锦囊牌<br /><b>时机</b>：出牌阶段<br /><b>目标</b>：一名其他角色<br /><b>效果</b>：将此牌置于目标角色判定区内。其判定阶段进行判定：若结果为黑桃，其受到2点雷电伤害，然后将【浮雷】置入弃牌堆。"
}

local nezha = General(extension, "investiture__nezha", "god", 4)

Fk:addPoxiMethod{
  name = "investiture__fuhai",
  card_filter = function(to_select, selected, data)
    if #selected == 0 then
      return Fk:currentRoom():getCardArea(to_select) == Card.DiscardPile
    else
      local card = Fk:getCardById(selected[1])
      if card.trueName == "slash" then
        return Fk:currentRoom():getCardArea(to_select) == Card.PlayerHand
      elseif card.trueName == "jink" then
        return Fk:currentRoom():getCardArea(to_select) == Card.PlayerEquip or Fk:currentRoom():getCardArea(to_select) == Card.PlayerJudge
      end
    end
  end,
  feasible = function(selected, data)
    if #selected > 0 then
      local card = Fk:getCardById(selected[1])
      if card.trueName == "slash" then
        return #selected == 4
      elseif card.trueName == "jink" then
        return #selected == 2
      end
    end
  end,
  prompt = "覆海：请选择【杀】再选择三张手牌，或选择【闪】再选择场上的牌"
}

local fuhai = fk.CreateActiveSkill{
  name = "investiture__fuhai",
  anim_type = "drawcard",
  prompt = "#investiture__fuhai",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards, _, _, player)
    local to = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and (to:getHandcardNum() > 2 or #to:getCardIds("ej") > 0 or player == to)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local cards = Fk:currentRoom():getBanner("@$CenterArea") or {}
    local slashs = table.filter(cards, function (id) return Fk:getCardById(id).trueName == "slash" end)
    local jinks = table.filter(cards, function (id) return Fk:getCardById(id).trueName == "jink" end)
    local fuhai_cards = table.simpleClone(slashs)
    if player ~= target and target:getHandcardNum() < 3 then fuhai_cards = {} end
    if player == target or #target:getCardIds("ej") > 0 then
      table.insertTableIfNeed(fuhai_cards, jinks)
    end
    if #fuhai_cards == 0 then return end
    if target == player then
      local id = room:askForCardChosen(player, player, { card_data = {{self.name, fuhai_cards}} }, self.name)
      if id then
        room:obtainCard(player, id, true, fk.ReasonJustMove, player.id, self.name)
      end
    else
      local chosen = room:askForPoxi(target, "investiture__fuhai", {
        { target.general, target:getCardIds("hej") },
        { "CenterArea", fuhai_cards },
      })
      if #chosen > 0 then
        local to_throw = table.filter(chosen, function (id) return room:getCardArea(id) ~= Card.DiscardPile end)
        local to_get = table.filter(chosen, function (id) return room:getCardArea(id) == Card.DiscardPile end)
        room:moveCardTo(to_throw, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, nil, true, target.id)
        room:moveCardTo(to_get, Card.PlayerHand, target, fk.ReasonJustMove, self.name, nil, true, target.id)
      end
    end
  end,
}

local zhichou = fk.CreateTriggerSkill{
  name = "investiture__zhichou",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseEnd, fk.Death},
  can_trigger = function(self, event, target, player, data)
    if event == fk.Death then
      return player:hasSkill(self) and data.damage and data.damage.from == player
      and table.contains(player:getTableMark("@[player]investiture__zhichou"), target.id)
    else
      if player:hasSkill(self) and target == player and player.phase == Player.Play then
        return #player:getTableMark("investiture__zhichou-turn") > 0--动态与标记
      end
    end 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.Death then
      data.extra_data = data.extra_data or {}
      data.extra_data.skip_reward_punish = true
      player:drawCards(3, self.name)
    else
      local mark = player:getTableMark("investiture__zhichou-turn")
      local to = room:getPlayerById(mark[1])
      table.removeOne(mark, mark[1])
      room:setPlayerMark(player, "investiture__zhichou-turn", mark)
      --Dozhichou(player, to)
      room:addTableMarkIfNeed(player, "zhichou_target-turn", to.id)
      room:doIndicate(player.id, {to.id})
      player:gainAnExtraPhase(Player.Play, true)
    end
  end,

  refresh_events = {fk.Damaged, fk.TurnStart, fk.EventPhaseEnd},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player then
      if event == fk.Damaged then
        if data.from and player.room.current and player.room.current ~= player then
          return #player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
            local damage = e.data[5]
            if damage and player == damage.from and data.from == damage.to then
              return true
            end
          end, Player.HistoryGame) == 0
        end
      elseif event == fk.TurnStart then
        return #player:getTableMark("@[player]investiture__zhichou") > 0
      else
        return #player:getTableMark("zhichou_target-turn") > 0
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.Damaged then
      player.room:addTableMarkIfNeed(player, "@[player]investiture__zhichou", data.from.id)
    elseif event == fk.TurnStart then
      local mark = player:getTableMark("@[player]investiture__zhichou")
      local players = table.filter(mark, function (id)
        return not player.room:getPlayerById(id).dead
      end)
      player.room:setPlayerMark(player, "investiture__zhichou-turn", players)
    else
      player.room:setPlayerMark(player, "zhichou_target-turn", 0)
    end
  end,
}

local zhichou_targetmod = fk.CreateTargetModSkill{
  name = "#nezha__zhichou_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    if card and to then
      return table.contains(player:getTableMark("zhichou_target-turn"), to.id)
    end
  end,
  bypass_distances = function(self, player, skill, card, to)
    if card and to then
      return table.contains(player:getTableMark("zhichou_target-turn"), to.id)
    end
  end,
}

zhichou:addRelatedSkill(zhichou_targetmod)

local kanhua = fk.CreateTriggerSkill{
  name = "investiture__kanhua",
}

fuhai.CenterArea = true
nezha:addSkill(fuhai)
nezha:addSkill(zhichou)
--nezha:addRelatedSkill(kanhua)

Fk:loadTranslationTable {
  ["investiture__kanhua"] = "看画",
  [":investiture__kanhua"] = "技能代码尚未完成，敬请期待",

  ["investiture__nezha"] = "哪吒",
  ["designer:investiture__nezha"] = "淼龙",
  ["investiture__fuhai"] = "覆海",
  ["#investiture__fuhai"] = "你可选择自己获得中央区内一张【杀】或【闪】或选择其他角色交换",
  [":investiture__fuhai"] = "阶段技，你可获得中央区内一张【杀】或【闪】；或令一名其他角色选择一项：1.用三张手牌交换中央区内一张【杀】；2.用一张其场上的牌交换中央区内一张【闪】。",
  ["investiture__fuhai_slash"] = "交换【杀】",
  ["investiture__fuhai_jink"] = "交换【闪】",
  ["CenterArea"] = "中央区",
  ["#investiture__fuhan-choose"] = "覆海：请选择一项和交换的牌",
  ["investiture__zhichou"] = "掷雠",
  ["@[player]investiture__zhichou"] = TT.colorString("掷雠", "red"),
  [":investiture__zhichou"] = "锁定技，你的回合外，你未对其造成过伤害的角色对你造成伤害后，你于额定出牌阶段后获得一个额外的出牌阶段，此阶段你对其使用牌无距离和次数限制，且你杀死其后奖惩改为摸三张牌。",
  ["#nezha__zhichou_prohibit"] = "掷雠",
}

-- 神·女娲
local nvwu = General(extension, "investiture__nvwa", "god", 3, 3, General.Female)
TT.loadGeneral(nvwu, { name = "女娲", reputation = "摶云補青", designer = "CYC", illustrator = "Jayron" })

--- 盘世
local panshi = fk.CreateTriggerSkill {
  name = "investiture__panshi",
  anim_type = "drawcard",
  events = {"fk.GeneralAppeared", fk.AfterCardsMove},
  can_trigger = function (self, event, target, player, data)
    if not player:hasShownSkill(self) then return end
    if event == "fk.GeneralAppeared" then
      return target == player
    else
      local total_move = 0
      for _, move in ipairs(data) do
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerHand then
              total_move = total_move + 1
              if total_move == player.hp then
                return true
              end
            end
          end
        end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == "fk.GeneralAppeared" then
      local center_cards = Fk:currentRoom():getBanner("@$CenterArea") or {}
      local missing_suits = table.filter({ "diamond", "club", "heart", "spade" }, function (s)
        return not table.find(center_cards, function (c) return Fk:getCardById(c):getSuitString() == s end)
      end)
      local cards = {}
      for _, s in ipairs(missing_suits) do
        local card = player.room:getCardsFromPileByRule(".|.|"..s, 1, "drawPile")
        if card then
          table.insertTableIfNeed(cards, card)
        end
      end
      if #cards > 0 then
        room:obtainCard(player, cards, true, fk.ReasonJustMove, player.id, self.name)
      end
    else
      room.logic:getCurrentEvent():findParent(GameEvent.Turn, true, Player.HistoryGame):addExitFunc(function ()
        TT.EnterHidden(player)
      end)
    end
  end,
}
panshi.isHiddenSkill = true
panshi.CenterArea = true

TT.loadSkill(panshi, {
  name = "盘世",
  detail = "隐匿。你登场后，从牌堆中随机获得中央区内缺少花色的牌各一张。你一次性失去不小于体力值张牌后，于当前回合结束时隐匿。"
})

nvwu:addSkill(panshi)

--- 囚龙
local qiulong_cards = { {"tuntian__broken_halberd", "tuntian__bee_cloth", "tuntian__brocade_box"}, {"tuntian__honey_trap", "duel", "fire_attack"} }

---@param room Room
---@param index integer
---@return Card[]
local getQiulong = function(room, index)
  local cards = {}
  for _, n in ipairs(qiulong_cards[index]) do
    local card = table.find(table.map(table.connect(room.void, room.draw_pile, room.discard_pile), Util.Id2CardMapper), function(c)
      return c.name == n
    end)
    if card then
      table.insertIfNeed(cards, card)
    end
  end
  return cards
end

---@param room Room
---@param index integer
---@param player ServerPlayer
---@param skillName string
local function doQiulong(room, index, player, skillName)
  local cards = getQiulong(room, index)
  if #cards > 0 then
    room:obtainCard(player, cards, true, fk.ReasonJustMove, player.id, skillName)
  end
  local stop
  repeat
    local inv, ret = room:askForUseActiveSkill(player, "qiulong_present", "#qiulong_present", true, { able_cards = table.map(cards, Util.IdMapper) }, true)
    if inv and ret then
      local card = ret.cards[1]
      local to = room:getPlayerById(ret.targets[1])
      U.presentCard(player, to, card)
    else
      stop = true
    end
  until stop or player.dead
end

local qiulong = fk.CreateTriggerSkill {
  name = "investiture__qiulong",
  anim_type = "switch",
  switch_skill_name = "investiture__qiulong",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player == target and player:hasSkill(self) and player.phase == Player.Finish and player:getMark("@@tuntian__readying:::"..self.name) == 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    doQiulong(room, player:getSwitchSkillState(self.name, true) + 1, player, self.name)
  end,
}
qiulong.TuntianReadySkill = true
TT.loadSkill(qiulong, {
  name = "囚龙",
  detail = "蓄势技，转换技，结束阶段，你可以获得：①【折戟】【引蜂衣】【锦盒】②【美人计】【决斗】【火攻】各一张并赠予其中任意张。"
})

nvwu:addSkill(qiulong)

local qiulong_present = fk.CreateActiveSkill{
  name = "qiulong_present",
  mute = true,
  can_use = Util.FalseFunc,
  card_num = 1,
  card_filter = function (self, to_select, selected, player)
    return #selected == 0 and table.contains(self.able_cards, to_select)
  end,
  target_num = 1,
  target_filter = function(self, to_select, selected, selected_cards, _, _, player)
    return #selected == 0 and to_select ~= player.id
  end,
}
Fk:addSkill(qiulong_present)

Fk:loadTranslationTable {
  ["#qiulong_present"] = "囚龙：可以将一张指定牌赠予其他角色",
  ["qiulong_present"] = "囚龙",
  ["@@tuntian__readying:::"..qiulong.name] = TT.colorString("囚龙", "gray")
}

return extension
